package class01;

/**
 * @description: 插入排序
 * @time: 2021/7/2 16:02
 * @author: lhy
 */
public class InsertSort {
    private static void swap(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    public static void insertSort(int[] arr){
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int end = 0; end < arr.length; end++) {
            for (int pre = end-1; pre >= 0 && arr[pre] > arr[pre+1]; pre--) {
                swap(arr,pre,pre+1);
            }
        }
    }

    public static void printArray(int[] arr){
        for (int value : arr) {
            System.out.print(value + " ");
        }
        System.out.println();
    }
    public static void main(String[] args) {
        int[] arr = {1,4,9,2,4,6,2,45,33};
        printArray(arr);
        insertSort(arr);
        printArray(arr);
    }
}
